using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using BBX.Common;
using BBX.Entity;
using BBX.Forum;
using System.Linq;

namespace BBX.Web
{
    public class showforum : PageBase
    {
        public List<Online> onlineuserlist;
        public List<Topic> topiclist = new List<Topic>();
        public List<Topic> toptopiclist = new List<Topic>();
        public List<IXForum> subforumlist = new List<IXForum>();
        //public List<PrivateMessageInfo> pmlist;
        public String onlineiconlist = OnlineList.GetOnlineGroupIconList();
        //public DataTable announcementlist = Announcements.GetSimplifiedAnnouncementList(Utils.GetDateTime(), "2999-01-01 00:00:00");
        public List<Announcement> announcementlist = Announcement.GetAvailableList();
        public String[] pagewordad = new String[0];
        public List<String> pagead = new List<String>();
        public String doublead;
        public String floatad;
        public String mediaad;
        public String quickeditorad = "";
        public String[] quickbgad;
        public IXForum forum;
        public UserExtcreditsInfo topicextcreditsinfo = new UserExtcreditsInfo();
        public UserExtcreditsInfo bonusextcreditsinfo = new UserExtcreditsInfo();
        public Int32 forumtotalonline;
        public Int32 forumtotalonlineuser;
        public Int32 forumtotalonlineguest;
        public Int32 forumtotalonlineinvisibleuser;
        public Int32 forumid = DNTRequest.GetInt("forumid", -1);
        public String forumnav = "";
        public Int32 showforumlogin;
        public Int32 pageid = DNTRequest.GetInt("page", 1);
        public Int32 forumpageid = DNTRequest.GetInt("page", 1);
        public Int32 topiccount;
        public Int32 pagecount = 1;
        public String pagenumbers = "";
        //public int toptopiccount;
        public String forumlistboxoptions;
        public Boolean showforumonline;
        public Boolean disablepostctrl;
        public Int32 parseurloff;
        public Int32 smileyoff;
        public Int32 bbcodeoff;
        public Int32 usesig = (ForumUtils.GetCookie("sigstatus") == "0") ? 0 : 1;
        /// <summary>每页主题数</summary>
        public Int32 tpp = ForumUtils.GetCookie("tpp").ToInt();
        /// <summary>每页帖子数</summary>
        public Int32 ppp = ForumUtils.GetCookie("ppp").ToInt();
        public Boolean ismoder;
        public String topictypeselectoptions;
        public Int32 topictypeid = DNTRequest.GetInt("typeid", -1);
        public String filter = DNTRequest.GetHtmlEncodeString("filter");
        public Boolean canposttopic;
        public Boolean canquickpost;
        public Boolean needlogin;
        public Int32 order = DNTRequest.GetInt("order", 1);
        public Int32 interval = DNTRequest.GetInt("interval", 0);
        public Int32 direct = DNTRequest.GetInt("direct", 1);
        //public string goodscategoryfid = (GeneralConfigInfo.Current.Enablemall <= 0) ? "{}" : MallPluginProvider.GetInstance().GetGoodsCategoryWithFid();
        public String topictypeselectlink;
        public String nextpage = "";
        public String navhomemenu = "";
        public IXForum[] visitedforums = Forums.GetVisitedForums();
        public Boolean showvisitedforumsmenu;
        public Boolean isnewbie;
        private String msg = "";
        //private string condition = "";
        //private string orderStr = "";
        public Int32 topicid;
        public Boolean needaudit;

        protected override void ShowPage()
        {
            GetPostAds(forumid);
            if (userid > 0 && useradminid > 0)
            {
                var adminGroupInfo = AdminGroup.FindByID(usergroupid);
                if (adminGroupInfo != null)
                {
                    disablepostctrl = adminGroupInfo.DisablePostctrl;
                }
            }
            if (forumid == -1)
            {
                base.AddLinkRss(forumpath + "tools/rss.aspx", "最新主题");
                base.AddErrLine("无效的版块ID");
                return;
            }
            forum = Forums.GetForumInfo(forumid);
            if (forum == null || forum.Fid < 1)
            {
                if (config.Rssstatus == 1)
                {
                    base.AddLinkRss(forumpath + "tools/rss.aspx", Utils.EncodeHtml(config.Forumtitle) + " 最新主题");
                }
                base.AddErrLine("不存在的版块ID");
                return;
            }
            if (config.Rssstatus == 1)
            {
                base.AddLinkRss(forumpath + "tools/" + Urls.RssAspxRewrite(forum.Fid), Utils.EncodeHtml(forum.Name) + " 最新主题");
            }
            if (JumpUrl(forum))
            {
                return;
            }
            needaudit = UserAuthority.NeedAudit(forum.Fid, forum.Modnewposts, useradminid, userid, usergroupinfo);
            if (useradminid > 0)
            {
                ismoder = Moderators.IsModer(useradminid, userid, forumid);
            }
            //this.SetSearchCondition();
            showforumlogin = IsShowForumLogin(forum);
            pagetitle = Utils.RemoveHtml(forum.Name);
            navhomemenu = Caches.GetForumListMenuDivCache(usergroupid, userid, config.Extname);
            forumnav = base.ShowForumAspxRewrite(ForumUtils.UpdatePathListExtname(forum.Pathlist.Trim(), config.Extname).Replace("\"showforum", "\"" + forumurl + "showforum"), forumid, pageid);
            topicextcreditsinfo = Scoresets.GetScoreSet(Scoresets.GetTopicAttachCreditsTrans());
            bonusextcreditsinfo = Scoresets.GetScoreSet(Scoresets.GetBonusCreditsTrans());
            if (forum.ApplytopicType == 1)
            {
                topictypeselectoptions = Forums.GetCurrentTopicTypesOption(forum.Fid, forum.Topictypes);
            }
            if (forum.ApplytopicType == 1)
            {
                topictypeselectlink = Forums.GetCurrentTopicTypesLink(forum.Fid, forum.Topictypes, forumurl + "showforum.aspx");
            }
            meta = PageHelper.UpdateMetaInfo(meta, forum.Seokeywords.IsNullOrEmpty() ? config.Seokeywords : forum.Seokeywords, forum.Seodescription.IsNullOrEmpty() ? forum.Description : forum.Seodescription, config.Seohead);
            SetEditorState();
            if (!UserAuthority.VisitAuthority(forum, usergroupinfo, userid, ref msg))
            {
                base.AddErrLine(msg);
                needlogin = (userid == -1);
                return;
            }
            canposttopic = UserAuthority.PostAuthority(forum, usergroupinfo, userid, ref msg);
            if (useradminid != 1 && !usergroupinfo.DisablePeriodctrl)
            {
                var text = "";
                if (canposttopic && Scoresets.BetweenTime(config.Postbanperiods, out text))
                {
                    canposttopic = false;
                }
                isnewbie = UserAuthority.CheckNewbieSpan(userid);
            }
            if ((config.Fastpost == 1 || config.Fastpost == 3) && !forum.AllowSpecialOnly && (userid < 0 || (canposttopic && !isnewbie)))
            {
                canquickpost = true;
            }
            if ((forum as XForum).Childs.Count > 0)
            {
                subforumlist = Forums.GetSubForumCollection(forumid, forum.ColCount, config.Hideprivate, usergroupid, config.Moddisplay);
            }
            if (!forum.Rules.IsNullOrWhiteSpace())
            {
                forum.Rules = UBB.ParseSimpleUBB(forum.Rules);
            }
            // 满足条件的主题数
            topiccount = Topic.SearchCount(forumid, topictypeid, interval, filter);
            if (tpp <= 0) tpp = config.Tpp;
            if (ppp <= 0) ppp = config.Ppp;
            if (pageid < 1) pageid = 1;

            // 内层板块，需要显示主题列表
            if (forum.Layer > 0)
            {
                // 置顶主题列表
                var tops = Topic.GetTop(forumid);
                if (tops.Count > 0)
                {
                    // 加上非本板块的主题数
                    topiccount += tops.Count(e => e.Fid != forumid);
                }

                // 根据主题总数计算分页
                //pagecount = ((topiccount % tpp == 0) ? (topiccount / tpp) : (topiccount / tpp + 1));
                pagecount = topiccount / tpp;
                if (topiccount % tpp > 0) pagecount++;
                if (pagecount == 0) pagecount = 1;
                if (pageid > pagecount) pageid = pagecount;

                // 如果有置顶主题，则先读取置顶主题，再读取部分普通主题以填满一页
                if (tops.Count > 0)
                {
                    // 置顶主题数
                    var toptopiccount = tops.Count;
                    // 置顶主题构成的完整页数，不包括半截
                    var topPageCount = toptopiccount / tpp;
                    // 置顶主题可能满好几页，如果分到当前页还有主题，则需要处理
                    if (toptopiccount > tpp * (pageid - 1))
                    {
                        // 取出本页所属的置顶主题
                        toptopiclist = Topics.GetTopTopicList(tops, tpp, pageid, forum.AutoClose, forum.Topictypeprefix);

                        if (toptopiclist.Count < tpp)
                            // 本页有一部分置顶主题，要注意计算本页普通主题的数量（总页大小-置顶帖在本页的大小），开始行很简单从0开始即可（因为是第一页普通主题）
                            topiclist = GetTopicInfoList(tpp - toptopiclist.Count, pageid - topPageCount, 0);
                    }
                    else
                        // 已经没有置顶主题，取满一页普通主题，注意开始行的计算
                        topiclist = GetTopicInfoList(tpp, pageid - topPageCount, toptopiccount % tpp);
                }
                else
                {
                    // 如果没有置顶主题，则直接读取一页普通主题
                    topiclist = GetTopicInfoList(tpp, pageid, 0);
                }
                // 如果没有主题，或者实际主题列表大于主题总数，那么更新论坛的主题数
                // 在XCode支持下，即使有缓存，这种可能性也很小很小
                if (topiclist == null || topiclist.Count == 0 || topiclist.Count > topiccount)
                {
                    XForum.SetRealCurrentTopics(forum.Fid);
                }
                SetPageNumber();

                var vs = visitedforums;
                showvisitedforumsmenu = (vs != null && ((vs.Length == 1 && vs[0].Fid != forumid) || vs.Length > 1));
                SetVisitedForumsCookie();
                Utils.WriteCookie("forumpageid", pageid.ToString(), 30);
                IsGuestCachePage();
            }
            forum.Description = UBB.ParseSimpleUBB(forum.Description);
            Online.UpdateAction(olid, UserAction.ShowForum, forumid, forum.Name, -1, "");
            if ((forumtotalonline < config.Maxonlinelist && (config.Whosonlinestatus == 2 || config.Whosonlinestatus == 3)) || DNTRequest.GetString("showonline") == "yes")
            {
                showforumonline = true;
                onlineuserlist = Online.GetList(forumid, Online._.UserID, true);

                var st = Online.GetStat();
                forumtotalonline = st.Total;
                forumtotalonlineuser = st.User;
                forumtotalonlineinvisibleuser = st.Invisible;
                forumtotalonlineguest = st.Guest;
            }
            if (DNTRequest.GetString("showonline") == "no")
            {
                showforumonline = false;
            }
            // 这里会导致版主列表不断增大，直到最后内存溢出，临时解决
            if (!forum.Moderators.IsNullOrWhiteSpace() && (forum.ModeratorsHtml.IsNullOrWhiteSpace() || !forum.ModeratorsHtml.Contains("href")))
            {
                var text2 = string.Empty;
                var array = forum.Moderators.Split(',');
                for (var i = 0; i < array.Length; i++)
                {
                    text2 += string.Format("<a href=\"{0}userinfo.aspx?username={1}\">{2}</a>,", forumpath, Utils.UrlEncode(array[i]), array[i]);
                }
                forum.ModeratorsHtml = text2.TrimEnd(',');
            }
            ForumUtils.UpdateVisitedForumsOptions(forumid);
        }

        private Boolean JumpUrl(IXForum forumInfo)
        {
            if (!forumInfo.Redirect.IsNullOrEmpty())
            {
                HttpContext.Current.Response.Redirect(forumInfo.Redirect);
                return true;
            }
            //if (this.config.Enablemall == 1 && forumInfo.IsTrade)
            //{
            //	MallPluginBase instance = MallPluginProvider.GetInstance();
            //	int goodsCategoryIdByFid = instance.GetGoodsCategoryIdByFid(forumInfo.ID);
            //	if (goodsCategoryIdByFid > 0)
            //	{
            //		HttpContext.Current.Response.Redirect(BaseConfigs.GetForumPath + Urls.ShowGoodsListAspxRewrite(goodsCategoryIdByFid, 1));
            //		return true;
            //	}
            //}
            return false;
        }

        public List<Topic> GetTopicInfoList(Int32 pageSize, Int32 pageIndex, Int32 startNumber)
        {
            return Topics.GetTopicList(forumid, topictypeid, interval, filter, order, direct != 0, pageSize, pageIndex, startNumber, 600, config.Hottopic, forum.AutoClose, forum.Topictypeprefix);
        }

        private void SetPageNumber()
        {
            if (String.IsNullOrEmpty(DNTRequest.GetString("search")))
            {
                if (topictypeid == -1)
                {
                    if (config.Aspxrewrite == 1)
                    {
                        if (filter.IsNullOrEmpty())
                        {
                            if (config.Iisurlrewrite == 0)
                            {
                                pagenumbers = Utils.GetStaticPageNumbers(pageid, pagecount, forum.Rewritename.IsNullOrEmpty() ? ("showforum-" + forumid) : (forumpath + forum.Rewritename), config.Extname, 8, (!forum.Rewritename.IsNullOrEmpty()) ? 1 : 0);
                            }
                            else
                            {
                                pagenumbers = Utils.GetStaticPageNumbers(pageid, pagecount, forum.Rewritename.IsNullOrEmpty() ? ("showforum-" + forumid) : (forumpath + forum.Rewritename), config.Extname, 8, (!forum.Rewritename.IsNullOrEmpty()) ? 2 : 0);
                            }
                            if (pageid < pagecount)
                            {
                                nextpage = string.Format("<a href=\"{0}{1}\" class=\"next\">下一页</a>", forumpath, Urls.ShowForumAspxRewrite(forumid, pageid + 1, forum.Rewritename));
                                return;
                            }
                        }
                        else
                        {
                            pagenumbers = Utils.GetPageNumbers(pageid, pagecount, string.Format("{0}showforum.aspx?forumid={1}&filter={2}", forumpath, forumid, filter), 8);
                            if (pageid < pagecount)
                            {
                                nextpage = string.Format("<a href=\"{0}showforum.aspx?forumid={1}&filter={2}&page={3}\" class=\"next\">下一页</a>", new Object[]
                                {
                                    forumpath,
                                    forumid,
                                    filter,
                                    pageid + 1
                                });
                                return;
                            }
                        }
                    }
                    else
                    {
                        pagenumbers = Utils.GetPageNumbers(pageid, pagecount, string.Format("{0}showforum.aspx?forumid={1}{2}", forumpath, forumid, filter.IsNullOrEmpty() ? "" : ("&filter=" + filter)), 8);
                        if (pageid < pagecount)
                        {
                            nextpage = string.Format("<a href=\"{0}showforum.aspx?forumid={1}{2}&page={3}\" class=\"next\">下一页</a>", new Object[]
                            {
                                forumpath,
                                forumid,
                                filter.IsNullOrEmpty() ? "" : ("&filter=" + filter),
                                pageid + 1
                            });
                            return;
                        }
                    }
                }
                else
                {
                    pagenumbers = Utils.GetPageNumbers(pageid, pagecount, string.Format("{0}showforum.aspx?forumid={1}&typeid={2}{3}", new Object[]
                    {
                        forumpath,
                        forumid,
                        topictypeid,
                        filter.IsNullOrEmpty() ? "" : ("&filter=" + filter)
                    }), 8);
                    if (pageid < pagecount)
                    {
                        nextpage = string.Format("<a href=\"{0}showforum.aspx?forumid={1}&typeid={2}{3}&page={4}\" class=\"next\">下一页</a>", new Object[]
                        {
                            forumpath,
                            forumid,
                            topictypeid,
                            filter.IsNullOrEmpty() ? "" : ("&filter=" + filter),
                            pageid + 1
                        });
                        return;
                    }
                }
            }
            else
            {
                pagenumbers = Utils.GetPageNumbers(pageid, pagecount, string.Format("{0}showforum.aspx?search=1&cond={1}&order={2}&direct={3}&forumid={4}&interval={5}&typeid={6}{7}", new Object[]
                {
                    forumpath,
                    DNTRequest.GetHtmlEncodeString("cond").Trim(),
                    order,
                    direct,
                    forumid,
                    interval,
                    topictypeid,
                    filter.IsNullOrEmpty() ? "" : ("&filter=" + filter)
                }), 8);
                if (pageid < pagecount)
                {
                    nextpage = string.Format("<a href=\"{0}showforum.aspx?search=1&cond={1}&order={2}&direct={3}&forumid={4}&interval={5}&typeid={6}{7}&page={8}\" class=\"next\">下一页</a>", new Object[]
                    {
                        forumpath,
                        DNTRequest.GetHtmlEncodeString("cond").Trim(),
                        order,
                        direct,
                        forumid,
                        interval,
                        topictypeid,
                        filter.IsNullOrEmpty() ? "" : ("&filter=" + filter),
                        pageid + 1
                    });
                }
            }
        }

        public void GetPostAds(Int32 forumid)
        {
            headerad = Advertisement.GetOneHeaderAd("", forumid);
            footerad = Advertisement.GetOneFooterAd("", forumid);
            pagewordad = Advertisement.GetPageWordAd("", forumid);
            pagead = Advertisement.GetPageAd("", forumid);
            doublead = Advertisement.GetDoubleAd("", forumid);
            floatad = Advertisement.GetFloatAd("", forumid);
            mediaad = Advertisement.GetMediaAd(templatepath, "", forumid);
            quickeditorad = Advertisement.GetQuickEditorAD("", forumid);
            quickbgad = Advertisement.GetQuickEditorBgAd("", forumid);
            if (quickbgad.Length <= 1)
            {
                quickbgad = new String[]
                {
                    "",
                    ""
                };
            }
        }

        private void SetEditorState()
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.Append("var Allowhtml=1;\r\n");
            smileyoff = forum.AllowSmilies ? 0 : 1;
            stringBuilder.Append("var Allowsmilies=" + (1 - smileyoff) + ";\r\n");
            bbcodeoff = ((forum.Allowbbcode == 1 && usergroupinfo.AllowCusbbCode) ? 0 : 1);
            stringBuilder.Append("var Allowbbcode=" + (1 - bbcodeoff) + ";\r\n");
            stringBuilder.Append("var Allowimgcode=" + forum.Allowimgcode + ";\r\n");
            base.AddScript(stringBuilder.ToString());
        }

        private Int32 IsShowForumLogin(IXForum forum)
        {
            var result = 1;
            if (forum.Password.IsNullOrEmpty())
            {
                result = 0;
            }
            else
            {
                if (Utils.MD5(forum.Password) == ForumUtils.GetCookie("forum" + forumid + "password"))
                {
                    result = 0;
                }
                else
                {
                    if (forum.Password == DNTRequest.GetString("forumpassword"))
                    {
                        ForumUtils.WriteCookie("forum" + forum.Fid + "password", Utils.MD5(forum.Password));
                        result = 0;
                    }
                }
            }
            return result;
        }

        private void SetVisitedForumsCookie()
        {
            if (forum.Layer > 0)
            {
                ForumUtils.SetVisitedForumsCookie(forum.Fid.ToString());
            }
        }

        public void IsGuestCachePage()
        {
            if (userid == -1 && pageid > 0 && pageid < pagecount && ForumUtils.IsGuestCachePage(pageid, "showforum"))
            {
                isguestcachepage = 1;
            }
        }
    }
}